﻿/// <reference path="jquery-1.10.1.min.js" />
var paramIds = {};
paramIds['deportName'] = $('#deportName');
$(document).ready(function () {

    var sale = {};
    sale["startDate"] = $("#startDate");
    sale["endDate"] = $("#endDate");
    sale["deportName"] = $("#deportName");
    sale["btn"] = $("#search");
    sale["msg"] = $("#msg");
    sale["salemaster"] = $("#salemaster");
    sale["deportN"] = $("#deportN");
    sale["dmonth"] = $("#dmonth");
    sale["dtbody"] = $("#dtbody");
    sale["detailExcel"] = $("#detailExcel");
    sale["masterExcel"] = $("#masterExcel");
    var date = new Date(), month = date.getMonth();
    sale.startDate.val(date.getFullYear().toString() + '-' + (month < 10 ? "0" + month : month));
    sale.endDate.val(date.getFullYear().toString() + '-' + ((month + 1) < 10 ? "0" + (month + 1) : (month + 1)));

    /*************按下enter键之后的事件*************/
    $('input.input-medium').keydown(function (e) {
        if (e === undefined) {
            if (event.keyCode === 13) {
                sale.btn.click();
            }
        }
        else {
            if (e.keyCode === 13) {
                sale.btn.click();
            }
        }
    });
    /*************按下enter键之后的事件*************/
    sale.btn.click(function () {
        if (sale.startDate.val().length === 0) {
            sale.msg.text("请输入开始日期").show().fadeOut(1000);
        } else if (sale.endDate.val().length === 0) {
            sale.msg.text("请输入结束日期").show().fadeOut(1000);
        } else if (sale.startDate.val().length !== 7) {
            sale.msg.text("开始日期的格式不正确，请输入格式为：2013-06的日期").show().fadeOut(5000);
        } else if (sale.endDate.val().length !== 7) {
            sale.msg.text("结束日期的格式不正确，请输入格式为：2013-06的日期").show().fadeOut(5000);
        } else if (sale.startDate.val() > sale.endDate.val()) {
            sale.msg.text("开始日期必须小于结束日期").show().fadeOut(2000);
        } else {
            var sdate = sale.startDate.val(), edate = sale.endDate.val(),
                    sy = parseInt(sdate.slice(0, 4)), sm = parseInt(sdate.slice(5)),
                    ey = parseInt(edate.slice(0, 4)), em = parseInt(edate.slice(5)),
                    mc = ey * 12 + em - sy * 12 - sm;
            var months = [], tmpm, tmpy = sy;
            months.push(sdate);
            for (var i = 1; i < mc; i++) {
                tmpm = sm + i;

                if (tmpm < 10) {
                    tmpm = "0" + tmpm;
                    months.push(sy + '-' + tmpm);
                }
                else if (parseInt(tmpm / 12) > 0) {//12...

                    if (tmpm % 12 > 0) {//13
                        tmpy = sy + parseInt(tmpm / 12);
                        tmpm = tmpm - 12 * parseInt(tmpm / 12);
                        tmpm = tmpm < 10 ? '0' + tmpm : tmpm;
                        months.push(tmpy + '-' + tmpm);
                    } else {//12
                        months.push(tmpy + '-' + 12);
                    }

                }
                else {
                    months.push(sy + '-' + tmpm);
                }
            }
            if (sdate !== edate) {
                months.push(edate);
            }
            var tbarr = new Array();
            tbarr.push(" <table id='saletb' class='table table-striped table-bordered table-hover' style='width:auto'><thead><tr><th>客户名称(月初-月末)</th><th>客户代码</th>");
            for (var j = 0; j < months.length; j++) {
                tbarr.push("<th>" + months[j] + "</th>");
            }
            tbarr.push("<th>总计</th></tr></thead>");
            sale.msg.text("正在查询...").show(1000);
            $.ajax({
                type: "POST",
                url: "WebHandler.ashx?type=search&rnd=" + Math.random(),
                data: { sd: sdate, ed: edate, deportId: paramIds.deportName.attr("title") },
                success: function (data) {
                    var json = $.parseJSON(data);
                    if (json.length === 0) {
                        tbarr.push("<tbody><tr><td colspan='" + (months.length + 3) + "'>没有查询到任何数据</td></tr></tbody></table>");
                    }
                    else {
                        var cd = '', sales = [], salearr = new Array();
                        cd = json[0].ClientId;
                        salearr["ClientId"] = cd;
                        salearr["ClientName"] = json[0].ClientName;

                        for (var j = 0; j < months.length; j++) {
                            if (json[0].Month === months[j]) {
                                salearr[months[j]] = json[0].Sale + '*' + json[0].BackSection;
                            }
                            else {
                                salearr[months[j]] = '0' + '*' + '0';
                            }
                        }
                        for (var i = 1; i < json.length; i++) {
                            if (json[i].ClientId === cd) {//同一个店铺的不同月份
                                for (var k = 0; k < months.length; k++) {
                                    if (json[i].Month === months[k]) {
                                        salearr[months[k]] = json[i].Sale + '*' + json[i].BackSection;
                                    }
                                    else {
                                        if (!salearr[months[k]]) {
                                            salearr[months[k]] = '0' + '*' + '0';
                                        }
                                    }
                                }
                                if (i === json.length - 1) {//考虑是否是最后一条数据
                                    salearr['total'] = 0;
                                    salearr['btotal'] = 0;
                                    for (var m = 0; m < months.length; m++) {
                                        var t = salearr[months[m]].split('*');
                                        salearr["total"] += parseFloat(t[0]);
                                        salearr['btotal'] += parseFloat(t[1]);
                                    }
                                    sales.push(salearr);
                                }
                            }
                            else {//这里是另一个店铺的
                                salearr['total'] = 0;
                                salearr['btotal'] = 0;
                                for (var m = 0; m < months.length; m++) {
                                    var t = salearr[months[m]].split('*');
                                    salearr["total"] += parseFloat(t[0]);
                                    salearr['btotal'] += parseFloat(t[1]);
                                }
                                sales.push(salearr);
                                salearr = {};
                                cd = json[i].ClientId;
                                salearr["ClientId"] = cd;
                                salearr["ClientName"] = json[i].ClientName;
                                for (var n = 0; n < months.length; n++) {
                                    if (months[n] === json[i].Month) {
                                        salearr[months[n]] = json[i].Sale + '*' + json[i].BackSection;
                                    }
                                    else {
                                        if (!salearr[months[n]]) {
                                            salearr[months[n]] = '0' + '*' + '0';
                                        }
                                    }
                                }
                            }
                        }
                        tbarr.push('<tbody>');
                        var tpmv;
                        $.each(sales, function (si, sv) {
                            tbarr.push("<tr><td  style='height:10px;'><button title='" + (sv.ClientId) + "' href='javascript:void(0)' class='btn btn-success'>删除</button>&nbsp;&nbsp;&nbsp;&nbsp;" + sv.ClientName + "</td><td>" + sv.ClientId + "</td>");
                            $.each(months, function (mi, mv) {
                                tpmv = sv[mv].split('*')[0];
                                if (tpmv === '0') {
                                    tbarr.push("<td>" + '——' + "</td>");
                                }
                                else {
                                    tbarr.push("<td>" + parseFloat(tpmv).toFixed(2) + "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <a href='#mydetail' role='button' title='" + sv.ClientName + '*' + sv.ClientId + '*' + mv + "'  data-toggle='modal'>明细</a></td>");
                                }

                            });
                            tpmv = sv.total;
                            if (tpmv === "0") {
                                tbarr.push("<td>" + "——" + "</td></tr>");
                            }
                            else {
                                tbarr.push("<td>" + parseFloat(sv.total).toFixed(2) + "</td></tr>");
                            }
                            tbarr.push("<tr><td>回款</td><td></td>");
                            $.each(months, function (mi, mv) {
                                tpmv = sv[mv].split('*')[1];
                                if (tpmv === "0") {
                                    tbarr.push("<td title='双击编辑,没有销售额的,保存回款后下次不会显示' id='" + mv + "' name='" + sv.ClientId + "'></td>");
                                }
                                else {
                                    tbarr.push("<td title='双击编辑' id='" + mv + "' name='" + sv.ClientId + "'>" + tpmv + "</td>");
                                }
                            });
                            tpmv = sv.btotal;
                            if (tpmv === 0) {
                                tbarr.push("<td id='" + sv.ClientId + "'></td></tr>");
                            }
                            else {
                                tbarr.push("<td id='" + sv.ClientId + "'>" + parseFloat(tpmv).toFixed(2) + "</td></tr>");
                            }
                        });
                        tbarr.push("<tr><td></td><td>销售汇总</td>");
                        for (var i = 0; i < months.length + 1; i++) {
                            tbarr.push("<td></td>");
                        }
                        tbarr.push("</tr>");
                        tbarr.push("<tr><td></td><td>回款汇总</td>");
                        for (var i = 0; i < months.length + 1; i++) {
                            tbarr.push("<td></td>");
                        }
                        tbarr.push("</tr>");
                        tbarr.push("</tbody>");
                    }
                    sale.salemaster.html(tbarr.join('')); //显示table
                    sale.msg.text("").hide(1000);
                    /***********************隐藏不需要的行****************************/
                    $("button.btn-success").click(function (e) {
                        var tmpa = $(this), tmpTr = tmpa.parent().parent(), tmpTrNext = tmpTr.next();
                        tmpTr.remove();
                        tmpTrNext.remove();
                        tongji(months)
                    });
                    /***********************隐藏不需要的行****************************/
                    tongji(months);

                    var tmpId, tmpName, tmpTb1, tmpTb2, tmpInput, orignalV;
                    /***********************回款单元格双击事件****************************/
                    $("#saletb tr:even td").dblclick(function () {
                        tmpTb1 = $(this);
                        tmpValue = tmpTb1.html();
                        tmpId = tmpTb1.attr('id');
                        tmpName = tmpTb1.attr('name');
                        tmpTb1.html("<input  type='text' class='input-small' value='" + tmpValue + "'/>");
                        tmpInput = $($("input.input-small").get(0));
                        tmpInput.focus();
                        orignalV = tmpInput.val();
                        /***********************keydown事情保存回款用的****************************/
                        tmpInput.keydown(function (e) {
                            var data = {}, url = 'WebHandler.ashx?type=back&rnd=' + Math.random();
                            if (e === undefined) {
                                if (event.keyCode === 13) {
                                    if (orignalV != tmpInput.val()) {
                                        data["month"] = tmpId;
                                        data["clientId"] = tmpName;
                                        data["backSection"] = tmpInput.val() === "" ? 0 : tmpInput.val();
                                        ajaxFuc('GET', url, data, sale);
                                    }
                                    tmpTb1.html(tmpInput.val());
                                    tongji(months);
                                }
                            }
                            else {
                                if (e.keyCode === 13) {
                                    if (orignalV != tmpInput.val()) {
                                        data["month"] = tmpId;
                                        data["clientId"] = tmpName;
                                        data["backSection"] = tmpInput.val() === "" ? 0 : tmpInput.val();
                                        ajaxFuc('GET', url, data, sale);
                                    }
                                    tmpTb1.html(tmpInput.val());
                                    tongji(months);
                                }
                            }
                        }).mouseleave(function () {
                            tmpValue = tmpInput.val();
                            if (orignalV != tmpValue) {
                                var data = {}, url = 'WebHandler.ashx?type=back&rnd=' + Math.random();
                                data["month"] = tmpId;
                                data["clientId"] = tmpName;
                                data["backSection"] = tmpValue === "" ? 0 : tmpValue;
                                ajaxFuc('GET', url, data, sale);
                                tmpTb1.html(tmpValue);
                            }
                            tmpTb1.html(tmpValue);
                            tongji(months);
                        });
                        /***********************keydown事情保存回款用的****************************/
                    });
                    /***********************回款单元格双击事件****************************/



                    /***********************查看销售明细****************************/
                    $("a").click(function (e) {
                        var titles = $(this).attr('title').split('*');
                        var clientName = titles[0], cd = titles[1], month = titles[2];
                        sale.deportN.text(clientName);
                        sale.dmonth.text(month);
                        $.ajax({
                            url: 'WebHandler.ashx?type=detail&rnd=' + Math.random(),
                            type: "POST",
                            data: { clientId: cd, month: month },
                            beforeSend: function () {
                                sale.dtbody.html("<tr><td colspan='7'>正在查询...</td></tr>");
                            },
                            success: function (data) {
                                var json = $.parseJSON(data);
                                if (json.length === 0) {
                                    sale.dtbody.html("<tr><td colspan='7'>没有查询到任何销售明细</td></tr>");
                                }
                                else {
                                    var htmlarr = new Array();
                                    var numSum = 0;
                                    $.each(json, function (index, value) {
                                        numSum += parseFloat(value.Number);
                                        htmlarr.push("<tr><td>" + (index + 1) + "</td><td>" + value.BillDate + "</td><td>" + value.Style.slice(0, 3) + "***" + value.Style.slice(6) + "</td><td>" + value.Number + "</td><td>" + value.Price + "</td><td>" + value.DataOrignal + "</td><td>" + value.MakeBillDate + "</td><td>" + value.Remark + "</td></tr>>");
                                    });
                                    htmlarr.push("<tr><td>汇总</td><td></td><td></td><td>" + numSum + "</td><td></td><td></td><td></td><td></td></tr>");
                                    sale.dtbody.html(htmlarr.join(''));

                                    /***********************导出销售明细的excel表格****************************/
                                    sale.detailExcel.click(function () {
                                        window.open("ExcelHelper.aspx?type=detail&clientId=" + cd + "&month=" + month + "&clientName=" + encodeURIComponent(clientName) + "&rnd=" + Math.random());
                                    });
                                    /***********************导出销售明细的excel表格****************************/

                                }
                            },
                            error: function (xhr, status, error) {
                                sale.dtbody.html("<tr><td colspan='7'>" + status + ':' + error + "</td></tr>");
                                //freezeTable("dtable", 2, 0, 760, 620);
                            }
                        });
                    });
                    /***********************查看销售明细****************************/

                    /***********************导出汇总报表excel****************************/
                    sale.masterExcel.click(function () {
                        window.open("ExcelHelper.aspx?type=master&clientId=" + paramIds.deportName.children('option:checked').val() + "&sdate=" + sdate + "&edate=" + edate + "&rnd=" + Math.random());
                    });
                    /***********************导出汇总报表excel****************************/
                }
            });
        }
    });

    /***********************获取店铺列表****************************/
    var index = 0,
    arr = new Array(), tmpjson = '';

    paramIds.deportName.mouseover(function () {
        var dns = paramIds.deportName.val();
        dns = dns.slice(0, dns.length - 1);
        var dnsarr = dns.split(',');
        if (index === 0) {
            $.ajax({
                url: 'WebHandler.ashx?type=deport&rnd=' + Math.random(),
                type: 'GET',
                success: function (data) {
                    var json = $.parseJSON(data);
                    tmpjson = json;
                    $.each(json, function (index, v) {
                        if ($.inArray(v.ClientName, dnsarr) > 0) {
                            arr.push("<input checked='checked' onclick='clickDeport(this)' name='" + v.ClientName + "' type='checkbox' value='" + v.ClientId + "' id='" + v.ClientId + "'/><label class='label label-success' for='" + v.ClientId + "'>" + v.ClientName + " </label><br/>");
                        }
                        else {
                            arr.push("<input onclick='clickDeport(this)' name='" + v.ClientName + "' type='checkbox' value='" + v.ClientId + "' id='" + v.ClientId + "'/><label class='label label-success' for='" + v.ClientId + "'>" + v.ClientName + " </label><br/>");
                        }

                    });
                    paramIds.deportName.popover({
                        title: "店铺列表",
                        html: true,
                        placement: "bottom",
                        content: arr.join('')
                    });
                    index = 1;
                }
            });
        }
        else {
            arr = new Array();
            $.each(tmpjson, function (index, v) {
                if ($.inArray(v.ClientName, dnsarr) < 0) {
                    arr.push("<input onclick='clickDeport(this)' name='" + v.ClientName + "' type='checkbox' value='" + v.ClientId + "' id='" + v.ClientId + "'/><label class='label label-success' for='" + v.ClientId + "'>" + v.ClientName + " </label><br/>");
                }
                else {
                    arr.push("<input checked='checked' onclick='clickDeport(this)' name='" + v.ClientName + "' type='checkbox' value='" + v.ClientId + "' id='" + v.ClientId + "'/><label class='label label-success' for='" + v.ClientId + "'>" + v.ClientName + " </label><br/>");

                }

            });
            paramIds.deportName.popover("destroy");
            paramIds.deportName.popover({
                title: "店铺列表",
                html: true,
                placement: "bottom",
                content: arr.join('')
            });
        }
    });
    /***********************获取店铺列表****************************/
});

function ajaxFuc(type, url, data, sale) {
    $.ajax({
        type: type,
        url: url,
        data: data,
        success: function (data) {
            if (data !== 'ok') {
                sale.msg.text("回款保存失败..." + data).fadeIn(1000);
            }
        },
        error: function (xhr, status, error) {
            sale.msg.text("回款保存出现异常..." + status + ":" + error).fadeIn(1000);
        }
    });
}

var tmpId = "", tmpN = "";
function clickDeport(obj) {
    var dp = $(obj);
    if (dp.is(":checked")) {
        tmpId += dp.attr("id") + ",";
        tmpN += dp.attr("name") + ",";
    } else {
        tmpId = tmpId.replace(dp.attr("id") + ",", "");
        tmpN = tmpN.replace(dp.attr("name") + ",", "");
    }
    paramIds.deportName.attr("title", tmpId).val(tmpN);
}

function tongji(months) {
    /***********************统计汇总信息****************************/
    var tmpRows = $("#saletb tr"), tmpRow, tmpCell, saleSum = 0, backSum = 0, tmpValue;
    console.log(tmpRows);
    for (var j = 2; j <= months.length + 3; j++) { //列循环
        saleSum = 0; backSum = 0;
        for (var i = 1; i < tmpRows.length - 2; i = i + 2) {//因为第一行是标题（行循环）
            tmpRow = tmpRows[i]; //获取行（销售行）
            tmpCell = $(tmpRow).children("td")[j]; //获取单元格
            tmpValue = $(tmpCell).text(); //获取单元格的值
            if (tmpValue.length > 2) {
                saleSum += parseFloat(tmpValue);
            }
            tmpRow = tmpRows[i + 1]; //回款行
            tmpCell = $(tmpRow).children("td")[j];
            tmpValue = $(tmpCell).text();

            if (tmpValue.length !== 0) {
                backSum += parseFloat(tmpValue);
            }
        }
        tmpRow = tmpRows[tmpRows.length - 2];
        tmpCell = $(tmpRow).children("td")[j];
        $(tmpCell).html(saleSum.toFixed(2));

        tmpRow = tmpRows[tmpRows.length - 1];
        tmpCell = $(tmpRow).children("td")[j];
        $(tmpCell).html(backSum.toFixed(2));
    }

    /***********************统计汇总信息****************************/

    /***********************颜色标注****************************/

    var tmp12v;
    for (var j = 2; j <= months.length + 2; j++) { //列循环
        for (var i = 1; i < tmpRows.length; i = i + 2) {//因为第一行是标题（行循环）
            tmpRow = tmpRows[i]; //获取行（销售行）
            tmpCell = $(tmpRow).children("td")[j]; //获取单元格
            tmpValue = $(tmpCell).text(); //获取单元格的值
            if (tmpValue.length > 2) {//说明是有销售额
                tmpValue = parseFloat(tmpValue);
                if ((j + 12) <= months.length + 12) {
                    tmpCell = $(tmpRow).children("td")[j + 12]; //今年和去年相比较的
                    tmp12v = $(tmpCell).text();
                    if (tmp12v.length > 2) {
                        tmp12v = parseFloat(tmp12v);
                        if (tmpValue * (1 - 0.1) >= tmp12v) {
                            $(tmpCell).css("color", "red");
                        }
                        else if (tmpValue * (1 + 1.5) >= tmp12v) {
                            $(tmpCell).css("color", "green");
                        }
                    }
                }
            }
            else { //说明是没有销售额的
                if ((j + 12) <= months.length + 2) {
                    tmpCell = $(tmpRow).children("td")[j + 12];
                    tmp12v = $(tmpCell).text();
                    if (tmp12v.length > 2) {
                        $(tmpCell).css("color", "green");
                    }
                }
            }
        }
    }
    /***********************颜色标注****************************/
}